import axios from 'axios'

const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api'  // Changed baseURL to use env variable or default to /api
})

export const uploadCSV = async (file) => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    const response = await api.post('/upload', formData)
    return response.data
  } catch (error) {
    if (error.response) {
      // Server responded with error
      throw new Error(error.response.data.message || '服务器处理文件失败')
    } else if (error.request) {
      // Request made but no response
      throw new Error('无法连接到服务器，请检查网络连接')
    } else {
      // Error in request setup
      throw new Error('文件上传失败：' + error.message)
    }
  }
}

export const fetchFilterOptions = async () => {
  try {
    const response = await api.get('/filter-options')
    return response.data
  } catch (error) {
    if (error.response) {
      throw new Error(error.response.data.message || '获取筛选选项失败')
    } else if (error.request) {
      throw new Error('无法连接到服务器，请检查网络连接')
    } else {
      throw new Error('获取筛选选项失败：' + error.message)
    }
  }
}

export const fetchData = async (filters) => {
  try {
    const response = await api.post('/data', filters)
    return response.data
  } catch (error) {
    if (error.response) {
      throw new Error(error.response.data.message || '获取数据失败')
    } else if (error.request) {
      throw new Error('无法连接到服务器，请检查网络连接')
    } else {
      throw new Error('获取数据失败：' + error.message)
    }
  }
}

export const getFilterOptions = async (queryString = '') => {
  try {
    const response = await api.get(`/filter-options-from-data${queryString}`)
    return response.data
  } catch (error) {
    if (error.response) {
      throw new Error(error.response.data.message || '获取筛选选项失败')
    } else if (error.request) {
      throw new Error('无法连接到服务器，请检查网络连接')
    } else {
      throw new Error('获取筛选选项失败：' + error.message)
    }
  }
}
